from django.shortcuts import render
from django.views import View
from django.http import HttpResponse,JsonResponse
from verifications.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from verifications.libs.yuntongxun.ccp_sms import CCP
import random
import re
from celery_tasks.sms.task import ccp_send_sms_code

class ImageCodeView(View):
    def get(self,request,uuid):
        text,image = captcha.generate_captcha()
        conn = get_redis_connection('verify_code')
        try :
            conn.setex('img_%s'%uuid,300,text)
        except Exception as e:
            print(e)
            return JsonResponse({'code':400,'errmsg':'redis数据库写入失败'},status=500)
        return HttpResponse(image,content_type='image/jpg')




class SMSCodeView(View):
    def get(slef, request,mobile):
        conn = get_redis_connection('verify_code')
        p1 = conn.pipeline()
        redis_flag = conn.get('send_flag_%s'%mobile)
        if redis_flag:
            return JsonResponse({'code': 400, 'errmsg': '请不要频繁进行短信验证'})
        p1.setex('send_flag_%s' % mobile, 60, 1)
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        if not all([mobile, image_code, uuid]):
            return JsonResponse({'code': 400, 'errmsg': '缺少参数'},status = 500)
        if not re.match(r'^[a-zA-Z0-9]{4}$', image_code):
            return JsonResponse({'code': 400, 'errmsg': '图形验证码参数错误'}, status=400)
        if not re.match(r'^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$', uuid):
            return JsonResponse({'code': 400, 'errmsg': 'uuid参数格式错误'}, status=400)

        user_text = conn.get('img_%s' % uuid)
        if not user_text:
            return JsonResponse({'code': 400, 'errmsg': '验证码过期'}, status=403)
        user_text = user_text.decode()
        conn.delete('img_%s' % uuid)
        if image_code.lower() != user_text.lower():
            return JsonResponse({'code': 400, 'errmsg': '图形验证码输入错误'}, status=403)
        num = '%06d' % random.randint(0, 999999)
        p1.setex('sms_%s' % mobile, 300, num)
        p1.execute()
        print
        # CCP().send_template_sms(mobile, [num, 5], 1)
        ccp_send_sms_code.delay(mobile,num)
        return JsonResponse({'code': 0, 'errmsg': '手机验证码发送成功'})


